package com.hdy.javachatroomdemo.factory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hdy.javachatroomdemo.Model.*;
import com.hdy.javachatroomdemo.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.List;
@Component("friendRequestTransferStrategy")
@Slf4j
public class FriendRequestTransfer extends AbstractMessageTransfer{

    @Autowired
    OnlineUserMapper onlineUserMapper;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    FriendMapper friendMapper;
    @Override
    public void sendMessage(MessageRequest request, User user) {
        //由于从前端获取的好友请求消息不完整,要进一步填充
        request.setType(Constants.FRIEND_REQUEST);
        request.setUsername(user.getUsername());
        request.setUserId(user.getUserId());
        //将好友请求保存到数据库中
        //先从数据库中查一下有没有相同的好友请求记录,如果有则不再存储
        System.out.println(request);
        List<MessageResponse> resp= friendMapper.queryFriendRequest(request);
        if(resp.size()>0){
            MessageResponse messageResponse = resp.get(0);
            System.out.println("好友请求已经存储过 userId:"+messageResponse.getFromId()+"friendId:"+messageResponse.getFriendId());
            return ;
        }
        //进行存储
        int ret=friendMapper.insertFriendRequest(request);
        System.out.println("好友请求添加完成,影响行数:"+ret);

        //获取好友session
        WebSocketSession friendSession= onlineUserMapper.get(request.getFriendId());
        //看看要添加的好友在不在线
        if(friendSession==null){
            //好友不在线,等到下次上线的时候在通过从数据库中获取好友请求的方式
            return;
        }
        //构造好响应信息
        MessageResponse messageResponse = new MessageResponse();
        messageResponse.setFriendId(request.getFriendId());
        messageResponse.setType(request.getType());
        messageResponse.setContent(request.getContent());
        messageResponse.setFromId(request.getUserId());
        messageResponse.setFromName(request.getUsername());
        try{
            //将消息转化成json字符串
            String jsonData=objectMapper.writeValueAsString(messageResponse);
            //将好友请求发送给好友
            friendSession.sendMessage(new TextMessage(jsonData));
        } catch (JsonProcessingException e) {
            log.error("处理好友请求时将消息转化json失败");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
